<?php

namespace Home\Service;

class ToiletService extends CommonService {

    public static $TAG = '厕所';

    public function getNearbyToiletsFromLBS($location, $radius = 100) {
        require VENDOR_PATH . 'LBS/search/NearbySearch.php';

        if (is_array($location)) {
            $location = implode(',', $location);
        }

        $search = new \NearbySearch($this->getGeoTableId(), $this->console, $location, $radius);

        $result = $search->search();
        if (0 == $result['status']) {
            $result['status'] = true;
            $result['data'] = $result['contents'];
            $result['msg'] = "OK, Location='{$location}', Radius={$radius}";
            unset($result['contents']);
        } else {
            $result['status'] = false;
            $result['msg'] = "Error, Location='{$location}', Radius={$radius}";
        }

        return $result;
    }

    public function create($toilet) {
        require VENDOR_PATH . 'LBS/geodata/PoiData.php';

        $name = $toilet['name'];
        $address = $toilet['address'];
        $latitude = $toilet['latitude'];
        $longitude = $toilet['longitude'];

        $Toilet = D('Toilet');
        $Toilet->startTrans();
        if ($toilet = $Toilet->create($toilet)) {
            if (flase === $Toilet->add($toilet)) {
                $Toilet->rollback();
                return $this->errorResult($Toilet->getDbError());
            }
        }

        $toilet['map_table_id'] = $Toilet->getLastInsId();
        $toilet['comment_count'] = 0;
        $toilet['like_count'] = 0;
        unset($toilet['name']);
        unset($toilet['address']);
        unset($toilet['latitude']);
        unset($toilet['longitude']);

        // 插入到LBS
        $column = new \PoiData($this->console, $this->getGeoTableId());
        $result = $column->create($name, $address, self::$TAG, $latitude,  $longitude, 1, $toilet);

        if ($result['status'] != 0) {
            $Toilet->rollback();
            return $this->errorResult('添加LBS厕所失败');
        }

        $Toilet->commit();
        return $this->resultReturn(true);
    }

    protected function getModelName() {
        return 'Toilet';
    }

    protected function getGeoTableId() {
        return 39958;
    }
}
